package com.woniu.qqmaster.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.qqmaster.entity.Qquser;
import com.woniu.qqmaster.mapper.QqUserMapper;
import com.woniu.qqmaster.utils.MyConstantsEnum;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @Author dlb
 * @Date 2022/12/29 11:37
 */
// 这只是一个普通的类，怎么把它标记为controller，并且还要交给spring管理？
@Log4j2
@Controller
public class UserController {

    @Autowired
    QqUserMapper qqUserMapper;

    // json 转换为对象 用什么类型对象？？
    // key，value，key ， value
    // Java k-v => map
    @ApiOperation("根据qqid和密码进行登录验证，返回json数据，200代表成功，201代表失败")
    @ResponseBody
    @RequestMapping(path = "/login",method = RequestMethod.POST)
    public Object login(@RequestBody Map<String , String> map, HttpSession session /* 自动注入进来的session对象 */) {

        HashMap m = CollectionUtils.newHashMap(1);  // hashMap默认容量大小是多少？   static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
        Optional<Object> o = Optional.ofNullable(session.getAttribute(MyConstantsEnum.USER.getValue())).map(e -> e);
        Qquser userBean =  null;
        if(!o.isPresent()) {
            userBean = qqUserMapper.login(map.get("uname"),map.get("upwd"));
            // e就是UserBean
            Optional.ofNullable(userBean).ifPresent(e-> session.setAttribute(MyConstantsEnum.USER.getValue(),e));
        } else {
            userBean = (Qquser) o.get();
        }
        // "msg"                        ,
        m.put(MyConstantsEnum.MSG.getValue() , Optional.ofNullable(userBean).map(e-> HttpServletResponse.SC_OK).orElse(HttpServletResponse.SC_CREATED));
        return m;
    }
}
